package belle.com.myapp.view.board.activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import belle.com.myapp.DataBase.DataBaseHelper;
import belle.com.myapp.R;
import belle.com.myapp.base.BaseActivity;
import belle.com.myapp.manager.ToolBarManager;
import belle.com.myapp.retrofit.ApiService;
import belle.com.myapp.view.board.activity.adapter.LeaderBoardAdapter;
import belle.com.myapp.view.board.activity.model.BoardBean;
import belle.com.myapp.view.board.activity.model.CollectList;
import belle.com.myapp.view.board.activity.model.LeaderBoardResponse;
import belle.com.myapp.view.board.activity.model.SongsBean;
import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 排行榜（数据塞入数据库后再取值）
 *
 * @author guanjiali1
 */
public class LeaderBoardActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rl_leader_board)
    RecyclerView rlLeaderBoard;

    private DataBaseHelper dataBaseHelper;
    private LeaderBoardAdapter leaderBoardAdapter;

    private List<BoardBean> list = new ArrayList<>();
    private List<SongsBean> list1 = new ArrayList<>();
    private List<CollectList> collectLists = new ArrayList<>();

    @Override
    protected int isTranslucentStatus() {
        return 0;
    }

    @Override
    protected boolean isNeedEventBus() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_leader_board;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ToolBarManager.setToolBack(this, toolbar, "排行榜");
        dataBaseHelper = new DataBaseHelper(this, "LeaderBoard.db", null, 1);

        //判断数据库表中是否有值，有值则话更新数据库
        if (dataBaseHelper.getReadableDatabase().compileStatement("SELECT COUNT(*) FROM music").simpleQueryForLong() > 1) {
            dataBaseHelper.onUpgrade(dataBaseHelper.getWritableDatabase(), 1, 2);
        }

        /**
         * recycleView初始化
         */
//        setRecyclerView();
    }

//    private void setRecyclerView() {
//        rlLeaderBoard.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
//        leaderBoardAdapter = new LeaderBoardAdapter(R.layout.item_board_list, );
//        rlLeaderBoard.setAdapter(leaderBoardAdapter);
//
//    }

    @Override
    protected void initData() {
        //网络请求
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://10.20.30.216:4000/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiService service = retrofit.create(ApiService.class);
        for (int i = 0; i <= 23; i++) {
            Call<LeaderBoardResponse> call = service.boardList(i);
            call.enqueue(new Callback<LeaderBoardResponse>() {
                @Override
                public void onResponse(@NonNull Call<LeaderBoardResponse> call, @NonNull Response<LeaderBoardResponse> response) {
                    //写入数据库
                    if (dataBaseHelper.getReadableDatabase().compileStatement("SELECT COUNT(*) FROM music").simpleQueryForLong() == 23) {
                        initSqlite(response);
                        query();
                    } else {
                        initSqlite(response);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<LeaderBoardResponse> call, @NonNull Throwable t) {
                    Log.d("LeaderBoardActivity", "t.getStackTrace():" + Arrays.toString(t.getStackTrace()));
                }
            });
        }

    }

    /**
     * 写入数据库
     */
    private void initSqlite(Response<LeaderBoardResponse> response) {
        ContentValues values = new ContentValues();
        if (response.body().getPlaylist() != null) {
            values.put("coverImgUrl", response.body().getPlaylist().getCoverImgUrl());
            values.put("musicId", response.body().getPlaylist().getId());
            values.put("name", response.body().getPlaylist().getName());
            dataBaseHelper.getWritableDatabase().insert("music", null, values);
        }

        ContentValues values2 = new ContentValues();
        values2.put("musicId", response.body().getPlaylist().getId());
        for (int j = 0; j < response.body().getPlaylist().getTracks().size(); j++) {
            values2.put("musicName", response.body().getPlaylist().getTracks().get(j).getName());
            values2.put("arName", response.body().getPlaylist().getTracks().get(j).getAr().get(0).getName());
            dataBaseHelper.getWritableDatabase().insert("Songs", null, values2);
        }
    }

    /**
     * 读取数据库，组装list
     */
    private void query() {
        SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
        Cursor cursor = db.query("music", null, null, null, null, null, null);
        Cursor cursor1 = db.query("Songs", null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                //遍历Cursor对象，取出数据
                int musicId = cursor.getInt(cursor.getColumnIndex("musicId"));
                String coverImgUrl = cursor.getString(cursor.getColumnIndex("coverImgUrl"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                BoardBean boardBean = new BoardBean();
                boardBean.setIds(musicId);
                boardBean.setUrl(coverImgUrl);
                boardBean.setName(name);
                list.add(boardBean);
            } while (cursor.moveToNext());
            Log.e("123", String.valueOf(list));
        }
        cursor.close();

        if (cursor1.moveToFirst()) {
            do {
                int musicId = cursor1.getInt(cursor.getColumnIndex("musicId"));
                String musicName = cursor1.getString(cursor1.getColumnIndex("musicName"));
                String arName = cursor1.getString(cursor1.getColumnIndex("arName"));
                SongsBean songsBean = new SongsBean();
                songsBean.setId(musicId);
                songsBean.setMusicName(musicName);
                songsBean.setArName(arName);
                list1.add(songsBean);
            } while (cursor1.moveToNext());
        }
        cursor1.close();
        for (BoardBean bean : list) {
            CollectList collect = new CollectList();
            collect.setName(bean.getName());
            collect.setUrl(bean.getUrl());
            List<SongsBean> charid = new ArrayList<>();
            for (SongsBean songsBean1 : list1) {
                SongsBean b = new SongsBean();
                if (bean.getIds() == songsBean1.getId()) {
                    b.setArName(songsBean1.getArName());
                    b.setMusicName(songsBean1.getMusicName());
                    charid.add(b);
                }
                collect.setSongs(charid);
            }
            collectLists.add(collect);
        }

    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }
}
